const createError = require('http-errors')
const fs = require('fs')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const session = require('express-session')
const RedisStore = require('connect-redis')(session)
const redisClient = require('./db/redis')

const blogRouter = require('./routes/blog')
const usersRouter = require('./routes/user')

const app = express()

// log日志
const ENV = process.env.NODE_ENV
if (ENV !== 'production') {
  // 开发环境
  app.use(
    logger('dev', {
      stream: process.stdout
    })
  )
} else {
  // 线上环境
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const writeStream = fs.createWriteStream(logFileName, {
    flags: 'a'
  })
  app.use(
    logger('combined', {
      stream: writeStream
    })
  )
}

// 返回格式json
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// cookie
app.use(cookieParser())

const sessionStore = new RedisStore({
  client: redisClient
})
// session
app.use(
  session({
    secret: 'HaiYang_9401177',
    cookie: {
      // path: '/', // 默认配置
      // httpOnly: true, // 默认配置
      maxAge: 24 * 60 * 60 * 1000
    },
    store: sessionStore
  })
)

// 路由
app.use('/api/blog', blogRouter)
app.use('/api/user', usersRouter)

// 路由错误, 返回 404
app.use((req, res, next) => {
  res.send('404 Not Found')
  next()
})

// 错误处理
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

module.exports = app
